package com.jwt.config;

import com.jwt.Filter.JwtAuthenticationTokenFilter;
import com.jwt.Handler.JwtLoginFailureHandler;
import com.jwt.Handler.JwtLoginSuccessHandler;
import com.jwt.Handler.MyAccessDeniedHandler;
import com.jwt.Handler.RestAuthenticationEntryPoint;
import com.jwt.service.UserService;
import jakarta.annotation.Resource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;

@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig {
	@Resource
	UserService userService;
	@Resource
	RestAuthenticationEntryPoint restAuthenticationEntryPoint;
	@Bean
	PasswordEncoder passwordEncoder(){
		return new BCryptPasswordEncoder();
	}
	@Resource
	JwtLoginSuccessHandler jwtLoginSuccessHandler;
	@Resource
	JwtLoginFailureHandler jwtLoginFailureHandler;
	@Resource
	MyAccessDeniedHandler accessDeniedHandler;
	@Bean
	SecurityFilterChain filterChain(HttpSecurity httpSecurity) throws Exception {
		JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter=new JwtAuthenticationTokenFilter();
		httpSecurity.addFilterBefore(jwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);
		httpSecurity.formLogin()
				.loginProcessingUrl("/doLogin")
				.successHandler(jwtLoginSuccessHandler)
				.failureHandler(jwtLoginFailureHandler)
				.permitAll()
				.and()
				.logout().permitAll()
				.and()
				.authorizeRequests()
				.anyRequest().authenticated()
				.and()
				.exceptionHandling().accessDeniedHandler(accessDeniedHandler)
				.and().headers().frameOptions().sameOrigin()
				.and().csrf().disable()
				.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
		httpSecurity.httpBasic().authenticationEntryPoint(restAuthenticationEntryPoint);
		httpSecurity.userDetailsService(userService);
		return httpSecurity.build();
	}
}
